package study.week05.gateway.outbound;

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpUtil;
import org.springframework.jms.core.JmsTemplate;
import study.week05.gateway.router.CustomRouter;

import java.util.concurrent.*;

import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;

public class OutboundHandler {

    CustomRouter router;
    ExecutorService proxyService;
    ResponseHandler requestHandler;

    public OutboundHandler(CustomRouter router, ExecutorService proxyService, ResponseHandler requestHandler) {
        this.router = router;
        this.proxyService = proxyService;
        this.requestHandler = requestHandler;
    }

    public void handleRequest(ChannelHandlerContext ctx, FullHttpRequest fullRequest){
        proxyService.execute(()->{
            //server地址通过aop注入，这里传null
            FullHttpResponse response = requestHandler.generateResponse(fullRequest, ctx,null);
            if(response != null){
                if (!HttpUtil.isKeepAlive(fullRequest)) {
                    ctx.write(response).addListener(ChannelFutureListener.CLOSE);
                } else {
                    response.headers().set(CONNECTION, KEEP_ALIVE);
                    ctx.write(response);
                }
                ctx.flush();
            }
        });
    }




}
